package model;

import java.util.ArrayList;
import java.util.Arrays;

import util.Stemmer;

/**
 * Implements the boolean method of search
 * @param String entrada - the boolean query in the Disjunctive Normal Form
 * @return ArrayList<String> - list of filenames which corresponds to the search 
 */

public class ModeloBooleano {

	
	InvIndex index;
	
	public ModeloBooleano(InvIndex indice) {
		this.index = indice;
	}
	
	public ArrayList<String> buscaBooleana(String entrada, boolean stem)
	{

		if(stem)
		{
			Stemmer stemmer = new Stemmer();
			entrada = stemmer.getStemmed(entrada);
		}
		
		
		ArrayList<String> resposta = new ArrayList<String>();
		
		String[] termos = entrada.split("\\|\\|");

		boolean[][] queries = new boolean[termos.length][];
		
		/*
		 * Aqui, quebro a string de entrada pelo caracter || (OR)
		 * Assim, fico com n "consultas" do tipo (p1 && !p2 && ...)
		 *
		 */
		
		for(int x=0;x<termos.length;x++) 
		{			

			termos[x] = termos[x].replace("(", "");
			termos[x] = termos[x].replace(")", "");
			termos[x] = termos[x].trim();

			//recupero cada palavra
			String[] words = termos[x].split("&&");

			queries[x] = new boolean[words.length]; //ARRAY REPRESENTATIVO DA CONSULTA
			
			for(int g = 0; g < words.length ; g++) 
			{
				
				String palavra = words[g].trim();

				if(palavra.charAt(0) == '!') 
					queries[x][g] = false;
				else 
					queries[x][g] = true;
				
			} //ARRAY DA CONSULTA PREENCHIDO
		
		}
		
		for(String fileName : index.getFileList()) 
		{ //VARRO ARQUIVO POR ARQUIVO
			
			for(int i=0; i < termos.length; i++) 
			{
				boolean[] doc = new boolean[queries[i].length]; //ASSOCIO A CADA ARQUIVO UM VETOR REPRESENTATIVO DA CONSULTA

				String[] words = termos[i].split("&&");
				for(int j = 0; j < words.length ; j++) 
					doc[j] = this.contains(words[j].replaceFirst("!", "").trim(),fileName); //ARRAY DA CONSULTA PREENCHIDO

					if(Arrays.equals(queries[i],doc)) 
						if(!resposta.contains(fileName))
							resposta.add(fileName);

			}

				
		} //ARRAY DO DOCUMENTO PREENCHIDO
					

		return resposta;
	}
	
	/**
	 * The contains method scans the Item TreeSet and returns if the given word exists in the given file.
	 * @param String word - The word being searched.
	 * @param String fileName - The name of the file that will be scanned.
	 * @return True if the file contains the word, or else False.
	 */
	public boolean contains(String word,String fileName)
	{ 
/*		if(this.repVetorial.contains(word, fileName) == 1)
			return true;
		else
			return false;
	}	*/
		
		if(index.getIndice().get(word) != null) {
			for(Item i: index.getIndice().get(word))
			{
				if(i.getFile().equals(fileName))
					return true;
			}
			
			return false;
		}
		else return false;
	}
	
}
